<!DOCTYPE html>
<html class="x-admin-sm">
<head>
  <meta charset="UTF-8">
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <link rel="stylesheet" href="/res/xadmin/css/font.css">
  <link rel="stylesheet" href="/res/xadmin/css/xadmin.css">
  <script src="/res/layui/layui.js" charset="utf-8"></script>
  <script type="text/javascript" src="/res/xadmin/js/xadmin.js"></script>
</head>
<body>
<div class="x-nav">
          <span class="layui-breadcrumb">
            <a href="#">首页</a>
            <a href="#">用户管理</a>
            <a>
              <cite>用户查询</cite></a>
          </span>
  <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
     onclick="location.reload()" title="刷新">
    <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
</div>
<div class="layui-fluid">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-body ">
          <div class="layui-form layui-col-space5">
            <div class="layui-inline layui-show-xs-block">
              <input type="text" id="username" placeholder="请输入用户名/账号" autocomplete="off"
                     class="layui-input">
            </div>
            <div class="layui-inline layui-show-xs-block">
              <button class="layui-btn" id="search"><i class="layui-icon">&#xe615;</i>
              </button>
            </div>
          </div>
        </div>
        <div class="layui-card-header">
          <button type="button" class="layui-btn layui-btn-sm">
            <i class="layui-icon">&#xe601;</i> 导出
          </button>
        </div>
        <div class="layui-card-body layui-table-body layui-table-main">

        </div>
        <div class="layui-card-body">
          <div id="tree"></div>
          <button class="layui-btn save-up" style="display: none;margin-top: 15px;">保存提交</button>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<script>
  layui.use(['layer', 'form', 'tree'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var tree = layui.tree;
    var mytree, username

    $('#search').on('click', function () {
      username = $('#username').val()
      if (username == null || username == '') {
        layer.msg('请输入用户名')
        return;
      }
      $.ajax({
        url: "/admin/companyService/" + username,
        success(data) {
          if (data.code != 0) {
            layer.msg(data.message)
            return false;
          }
          $('.save-up').show()
          var treedata = listToTree(data.data, '0');
          console.log(treedata)
          mytree = tree.render({
            elem: '#tree'  //绑定元素
            , id: 'treeIndex' //定义索引
            , showCheckbox: tree
            , data: treedata
          });
        }
      })
    })

    $('.save-up').on('click', function () {
      var d = mytree.getChecked('treeIndex')
      d = treeToList(d)
      var list = []
      for (var i = 0; i < d.length; i++) {
        list.push(d[i].id);
      }
      $.ajax({
        data: {username: username, list: list},
        url: '/admin/updateDataPermission',
        traditional: true, //默认false
        type: 'post',
        success(data) {
          if(data.code==0){
            layer.msg(data.message)
            return ;
          }
          layer.msg(data)
        }
      })
    })
  });

  function listToTree(arr, parentId) {
    arr.forEach(element => {
      let pid = element.pid;
      if (pid != parentId) {
        arr.forEach(ele => {
          if (ele.id == pid) { //当内层循环的ID== 外层循环的pid时，（说明有children），需要往该内层id里建个children并push对应的数组；
            if (!ele.children) {
              ele.children = [];
            }
            ele.children.push(element);
          }
        });
      }
    });
    //console.log(arr) //此时的数组是在原基础上补充了children;
    arr = arr.filter(ele => ele.pid == parentId); //这一步是过滤，按树展开，将多余的数组剔除；
    //console.log(arr)
    return arr;
  }

  /**
   * 树转list
   */
  function treeToList(tree) {
    for (var i in tree) {
      var node = tree[i];
      list = [];  //结果lsit
      if (node.children.length !== 0) {  //遍历树的第一层,只有一个根结点
        //第一层加入到list中,因为根结点模块设置为虚拟结点,所以不用加入
        /*list.push({
            id: node.id,
            name: node.title,
            parentId:node.parentId
        });*/
        toListDF(node.children, list, node.id);  //遍历子树,并加入到list中.
      }
    }
    return list;
  }

  /**
   * 深度优先遍历树
   * 一个递归方法
   * @params tree:要转换的树结构数据
   * @params list:保存结果的列表结构数据，初始传list = []
   * @params parentId:当前遍历节点的父级节点id，初始为null(因为根节点无parentId)
   **/
  function toListDF(tree, list, parentId) {
    for (var i in tree) { //遍历最上层
      //将当前树放入list中
      var node = tree[i];
      list.push({
        id: node.id,
        name: node.title,
        parentId: parentId
      });
      //如果有子结点,再遍历子结点
      if (node.children != null && node.children.length !== 0) {
        toListDF(node.children, list, node.id)  //递归
      }
    }
  }
</script>
</html>
